package com.chang.multithread.Safe;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class sync {
    /*//不使用类对象是
    static int count=0;
    static Object lock=new Object();*/

    public static void main(String[] args) throws InterruptedException {
        Room room=new Room();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
               /* synchronized (lock) {  //创建的对象就是同步锁，如果没有创建对象，则当前类.class(或者this)就是同步锁
                    //保证了临界区代码的原子性
                    count++;
                }*/
                room.increment();
            }
        });

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                /*synchronized (lock){
                count--;
                }*/
                room.decrement();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("count:{}",room.getCount());
    }
}
class Room{
    //synchronize标在成员方法上，锁住的是this对象。标在静态方法上，锁住的是当期类
    private  int count=0;
    public void increment(){
        synchronized (this){
            count++;
        }
    }
    public void decrement(){
        synchronized (this){
            count--;
        }
    }
    public int getCount(){
        synchronized (this) {
       return count;
        }
    }
}
